package vn.qnamuni.calendar.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Locale;
import vn.qnamuni.calendar.activity.R;
import vn.qnamuni.calendar.adapters.CalendarAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CalendarActivity extends Activity {
	
	public GregorianCalendar month, itemmonth;// calendar instances.

	public CalendarAdapter adapter;// adapter instance
	public Handler handler;// for grabbing some event values for showing the dot
							// marker.
	public ArrayList<String> items; // container to store calendar items which
									// needs showing the event marker

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendar);
		
		getActionBar().hide();
		Locale.setDefault( Locale.US );
		month = (GregorianCalendar) GregorianCalendar.getInstance();
	    itemmonth = (GregorianCalendar) month.clone();

		items = new ArrayList<String>();
		adapter = new CalendarAdapter(this, month);
		GridView gridview = (GridView) findViewById(R.id.cal_gridview);
		gridview.setAdapter(adapter);
			
		handler = new Handler();
		handler.post(calendarUpdater);

		final Button title = (Button) findViewById(R.id.cal_title);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
		//button trước
		ImageView previous = (ImageView) findViewById(R.id.cal_previous);
		previous.setOnClickListener(new OnClickListener() {
				
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setPreviousMonth();
				refreshCalendar();
			}
		});
		//Button next
		ImageView next = (ImageView) findViewById(R.id.cal_next);
		next.setOnClickListener(new OnClickListener() {
				
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setNextMonth();
				refreshCalendar();
			}
		});
			
		//Thiết lập sự kiện cho GridView
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				//"position" là phần tử được chọn trong GridView 
				((CalendarAdapter) parent.getAdapter()).setSelected(v);
				String selectedGridDate = CalendarAdapter.dayString.get(position);
				//căt "-" ra khỏi chuổi dd-MM-yyyy
				String[] separatedTime = selectedGridDate.split("-");
				// lấy về dd
				String gridvalueString = separatedTime[0].replaceFirst("^0*","");
				int gridvalue = Integer.parseInt(gridvalueString);
				// navigate to next or previous month on clicking offdays.
				if ((gridvalue > 10) && (position < 8)) {
					setPreviousMonth();
					refreshCalendar();
				} else if ((gridvalue < 7) && (position > 28)) {
					setNextMonth();
					refreshCalendar();
				}
				((CalendarAdapter) parent.getAdapter()).setSelected(v);

				showToast(selectedGridDate);
				//.....
				Intent i = new Intent(getApplicationContext(), EventActivity.class);
				// passing array index
				i.putExtra("id", selectedGridDate);
				startActivity(i);

			}
		});
		
	}
	
	public void showToast(String day){
		Toast.makeText(CalendarActivity.this,day,Toast.LENGTH_SHORT).show();
	}
	
	protected void setNextMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMaximum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) + 1),
					month.getActualMinimum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) + 1);
		}

	}

	protected void setPreviousMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}

	}
	public void refreshCalendar() {
		TextView title = (TextView) findViewById(R.id.cal_title);

		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generate some calendar items

		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}
	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();

			// Print dates of the current week
			DateFormat df = new SimpleDateFormat("dd-MM-yyyy",Locale.US);
			String itemvalue;
			for (int i = 0; i < 7; i++) {
			    itemvalue = df.format(itemmonth.getTime());
				itemmonth.add(GregorianCalendar.DATE, 1);
				items.add("12-09-2012"); 
				items.add("07-10-2012"); 
				items.add("15-10-2012"); 
				items.add("20-10-2012"); 
				items.add("30-11-2012"); 
				items.add("28-11-2012"); 
			}

			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};

	// Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.calendar, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		
		Intent intent;
		
		switch(item.getItemId()){
		case R.id.mnAbout:
			intent = new Intent().setClass(this, AboutActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			return true;
		case R.id.mnTasklist:
			intent = new Intent().setClass(this, ListActivity.class);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
		
	}

}
